package com.dish.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

public class JDBCUtils {

	private static DataSource myDataSource=null;
	private static JDBCUtils  jdbcUtils= new JDBCUtils();
	
	/**
	 * 构造函数设置为private，防止从外界再new
	 */
	private JDBCUtils(){
		InputStream inputStream= JDBCUtils.class.getClassLoader()
				.getResourceAsStream("dbconfig.properties");
		Properties prop = new Properties();
		try {
			prop.load(inputStream);
			myDataSource=BasicDataSourceFactory.createDataSource(prop);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static JDBCUtils getJDBCUtils(){
		return jdbcUtils;
	}
	
	/**
	 * 获取连接
	 * @return
	 */
	public static Connection getConnection(){
		Connection connection=null;
		try {
			connection=myDataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
		
	}
	
	/**
	 * 释放资源
	 * @param rs
	 * @param ps
	 * @param conn
	 */
	public static void free(ResultSet rs, PreparedStatement ps, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
